﻿using chat_app.NhibernateLogic.Entities;
using chat_app.NhibernateLogic.Managers;
using Microsoft.AspNet.SignalR;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace chat_app.Hubs
{
    public class Chat : Hub
    {

        private static Dictionary<string, string> nicks = new Dictionary<string,string>();
        
        public override System.Threading.Tasks.Task OnConnected()
        {
            var my_nick = Context.Request.QueryString["nick"];

            if(nicks.ContainsValue(my_nick))
            {
                Clients.Client(Context.ConnectionId).isnotaviable(1);
                return base.OnConnected();
            }

            nicks.Add(Context.ConnectionId, my_nick);

            Clients.Client(Context.ConnectionId).getMyConn(my_nick);

            //foreach(var item in all_messages)
            //    Clients.Client(Context.ConnectionId).loadhistory(item.ConnectionId, item.Message, item.Date);

            foreach (var item in nicks)
            {
                if (item.Key != Context.ConnectionId)
                Clients.Client(Context.ConnectionId).connect(item.Key,DateTime.UtcNow.ToShortTimeString(), "User " + nicks[item.Key] + " is connected now !",string.Empty,item.Value );
            }
            Clients.Others.connect(Context.ConnectionId,DateTime.UtcNow.ToShortTimeString(), "User " + nicks[Context.ConnectionId] + " is connected now !", string.Empty, nicks[Context.ConnectionId]);

            return base.OnConnected();
        }

        public void Send(string recipient_id,string message)
        {
            Action<string> sender_func = (nick_or_connId) => {
                
             ContentManager.SaveItem<ChatMessage>(CreateNewLocalMessage(Context.ConnectionId.ToString(), DateTime.Now.ToShortTimeString(), message));
            Clients.Client(nick_or_connId).newMessage(nicks[Context.ConnectionId],message,DateTime.UtcNow.ToShortTimeString());
            Clients.Caller.callerMessage(nicks[Context.ConnectionId], message, DateTime.UtcNow.ToShortTimeString());
                
            };

            var res = nicks.FirstOrDefault(x => x.Value == recipient_id);
            if (res.Value != string.Empty)
            {
                sender_func(res.Key);
            }
            else
            {
                sender_func(res.Key);
            }
           
        }

        public override System.Threading.Tasks.Task OnDisconnected()
        {
            //Clients.All.connect(DateTime.UtcNow.ToShortTimeString(), "User " + nicks[Context.ConnectionId] + " is disconnected from website !");
            nicks.Remove(Context.ConnectionId);
            Clients.All.removeonlineuser(Context.ConnectionId);
            return base.OnDisconnected();
        }

        public ChatMessage CreateNewLocalMessage(string connId, string date, string message)
        {
            return new ChatMessage(connId, date, message);
        }

        public void Type(string recipient_user, int type_message)
        {
            Clients.Client(recipient_user).typing(type_message);
        }

        public void Load(string connectionId)
        {
            var all_items = ContentManager.GetAllItems<ChatMessage>().Where(x => x.ConnectionId == connectionId).OrderBy(x => x.Date);
            Clients.Client(Context.ConnectionId).loadhistoryby(JsonSerializer.SerializeToString(all_items));
        }

    }

    public enum NickType
    {
        ConnectionId,
        StringNick
    }
}